#include "FixPlugin.h"

void FixPlugin::Start(){
	EnableBroadcast();
}

int FixPlugin::OnBroadcast(int windowID, char* subwindow, char* event, message_t* msg){
	if (IsIncomingPrivateMessage(msg) && HasBug(msg)){
		bool fixed = false;
		char* fixedText = GetFixedText(msg->text, &fixed);
		if (fixed){
			int res = CMDReceive(	msg->medium, 
									msg->connection_id, 
									msg->name, 
									msg->type, 
									fixedText, 
									msg->window_id, 
									msg->time_stamp);
		}
		delete[] fixedText;
	}
	return 0;
}

char* FixPlugin::GetFixedText(char* badInput, bool *fixed){
	//Actually bug is because unencessary conversion win1252 -> UTF8 is performed.
	//So we perform it back.
	int badInputLength = strlen(badInput);
	int bufferLength = badInputLength*2;
	WCHAR* wBuffer = new WCHAR[bufferLength];
	//UTF8 -> WideChar
	MultiByteToWideChar( CP_UTF8, 0, badInput, badInputLength+1, wBuffer, bufferLength);
	int resultLength = bufferLength;
	char* result = new char[resultLength];
	BOOL usedDefaultCharacter = false;
	//WideChar -> 1252
	WideCharToMultiByte( 1252, 0, wBuffer, bufferLength, result, resultLength, NULL, &usedDefaultCharacter);

	bool isFixed = false;
	bool eq = strequal(badInput, result);
	if (eq){
		isFixed = false;
	} else {
		isFixed = true;
	}
	delete[] wBuffer;
	*fixed = isFixed;
	return result;
}

char BUG_SIGNATURE[] = {0xc3,0x90,0x00};

bool FixPlugin::HasBug(message_t* msg){
	return (strstr(msg->text, BUG_SIGNATURE) != NULL);
}

const char* FixPlugin::GetName(){
	return "TrillFix";
}
const char* FixPlugin::GetCompany(){
	return "Macloud E-Mail: macloud@mail.ru";
}
const char* FixPlugin::GetVersion(){
	return "1.0";
}
const char* FixPlugin::GetDescription(){
	return "This plugin fixes bug that sometimes produces incorrect displaying of messages received from old versions of ICQ clients.\n Stop eating bodies of killed animals. Go Vegetarian!";
}

char* FixPlugin::GetGUID(){
	return "C3F9E502-4F80-4749-8FF7-593FD11E732D";
}